var express = require('express');
var router = express.Router();
var sql = require('./../sql')
var Address = require('./../sql/address')
var uuid = require('node-uuid')

//地址管理
router.get('/', function (req, res, next) {
    // let { userid,addressid,flag} = req.query
    // flag = flag * 1 || 0
    let addressid = req.query.addressid
    let flag =req.query.flag
    let shuju = { userid: req.query.userid}
    if (addressid) {
        shuju.addressid = addressid
    }
    if (flag) {
        shuju.flag = flag * 1
    }
    console.log(shuju)
    sql.find(Address, shuju, { _id: 0 }).then(data => {
        if (data.lenth === 0) {
            res.send({
                message: "没有默认地址",
            })
        } else {
            res.send({
                code: '200',
                message: '获取地址成功',
                data: data
            })
        }
    })
})
//修改和添加地址
router.post('/add', (req, res, next) =>{
    let { userid, name, tel, address, flag } = req.body
    console.log(flag)
    if (flag) {
        console.log(1)
        sql.update(Address, {userid},{$set:{flag:0}},'updateMany')
    }
    let addressid = 'address_' + uuid.v1()
    sql.insert(Address, { userid, name, tel, address, flag, addressid }).then(() => {
        res.send({
            code: '200',
            message: '添加地址成功'
        })
    })
})
router.get('/delete', (req, res, next) =>{
    let  addressid  = req.query.addressid
    console.log(addressid)
    sql.delete(Address, { addressid:addressid}).then(() => {
        res.send({
            code: '200',
            message: '删除地址成功'
        })
    })
})
router.post('/update', (req, res, next) =>{
    let { addressid, userid, name, tel, address, flag } = req.body
    if (flag == 1) {
        sql.update(Address, {userid},{$set:{flag:0}},"updateMany")
    }
    sql.update(Address, { addressid },{$set: {userid: userid, name: name, tel: tel, address: address, flag: flag}}).then(() => {
        res.send({
            code: '200',
            message: '修改地址成功'
        })
    })
})

module.exports = router;